package com.gz.furnitures.filter;

import com.google.gson.Gson;
import com.gz.furnitures.entity.Admin;
import com.gz.furnitures.entity.Member;
import com.gz.furnitures.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebFilter(urlPatterns = {"/views/cart/*", "/views/manage/*",
                          "/views/member/*", "/views/order/*",
                          "/cartServlet","/manage/furnServlet","/orderServlet"},
initParams = {  @WebInitParam(name="excludedUrls",
            value = "/views/manage/manage_login.jsp,/views/member/login.jsp")})
public class AuthFilter implements Filter {
    private List<String> excludedUrls;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludedUrls = filterConfig.getInitParameter("excludedUrls");
        //用逗号分割获取所有允许的url
        String[] splitUrls = excludedUrls.split(",");
        //将splitUrls转成List
        this.excludedUrls = Arrays.asList(splitUrls);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //通过request获取信息，首先先将servletRequest转成HttpServletRequest,才能获取到request
        HttpServletRequest request=(HttpServletRequest)servletRequest;

        //得到请求的url
        //ajax是在服务器端，所以ajax发送的request不是浏览器的request请求
        //所以过滤器对request的请求转发或重定向不会影响浏览器，即浏览器毫无反应
        //ajax请求体中未设置url,故这里的url为空
        String url = request.getServletPath();

        if (excludedUrls.contains(url)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //得到session中member对象
        Member member = (Member)request.getSession().getAttribute("member");
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (member == null && admin == null) {
            //说明该用户没登录过
            //注意，转发不走过滤器，如果写成重定向那么连"/views/member/login.jsp"都访问不了，
            // 因为过滤器限制了这个地址，故会无限循环
            //如果不是ajax请求
            if(!WebUtils.isAjaxRequest(request)) {
                request.getRequestDispatcher("/views/member/login.jsp").
                        forward(servletRequest, servletResponse);
            }else{
                //返回一个url，按照json格式
                Map<String,Object> resultmap = new HashMap<>();
                resultmap.put("url","views/member/login.jsp");
                String resultJson = new Gson().toJson(resultmap);
                servletResponse.getWriter().write(resultJson);
            }
            //返回
            return;
        } else if (member != null &&admin==null) { //如果以用户身份访问管理员页面，那么要处理
            //根据url判断用户是否访问了管理页面
            //这里我就根据自己的简单逻辑来了，即如果含有manage字段即返回首页
            if(url.contains("manage")){
                request.getRequestDispatcher("/index.jsp").
                        forward(servletRequest, servletResponse);
            }
        }
        //继续访问
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
